package com.bnlr.nohttp;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;


public abstract class CustomJavaHttpListener<T> implements HttpListener<String> {

    private JSONObject object;
    private Context context;
    private boolean isGson;
    private Class<T> dataM;


    public CustomJavaHttpListener(Context context, boolean isGson, Class<T> dataM) {
        this.context = context;
        this.isGson = isGson;
        this.dataM = dataM;

    }

    @Override
    public void onSucceed(int what, Response<String> response) {
        if (response.get().equals("")) {
            Log.i("onSucceed", "请求为空：请检查服务器！\n");
        } else {
            Log.i("onSucceed", "请求成功：\n" + response.get());
        }
        try {
            if (!response.get().equals("")) {
                object = new JSONObject(response.get());
                if (dataM == null && object.getInt("statusCode") != 0) {
                    return;
                }
                if (object.getInt("statusCode") == 0) {
                    if (isGson && dataM != null) {
                        Gson gson = new Gson();
                        doWork(gson.fromJson(object.toString(), dataM), object.getInt("statusCode"));
                    } else {
                        doWork((T) object, object.getInt("statusCode"));
                    }
                }
            }
        } catch (Exception e) {
            Log.i("onSucceed", "catch 异常  \n" + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (object != null) {
                    Log.i("onSucceed", "finally object is " + object);
                    if (object.getInt("statusCode") == 0) {
                        onFinally(object.getString("message"), object.getInt("statusCode"), true);
                    } else {
                        onFinally(object.getString("message"), -1, true);
                    }
                }
            } catch (JSONException e) {
                Log.i("onSucceed", "finally catch 异常  \n" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public abstract void doWork(T data, int code);

    public void onFinally(String obj, int code, boolean isSucceed) throws JSONException {
    } // 解析完成，如要执行操作，可重写该方法。

    @Override
    public void onFailed(int what, Response<String> response) {
        //Log.i("onFailed", "请求失败：\n" + response.get());

        // Toast.makeText(context, "网络请求数据失败", Toast.LENGTH_SHORT).show();
        try {
            onFinally("请求失败", -1, false); // json数据为空
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
